<template>
  <view class="oneClick">
    <classifyHead title="一键预约" />
    <view class="content">
      <!-- 今日可用积分 -->
      <view class="middle" style="margin-top: 20rpx">
        <view style="color: aliceblue; margin-left: 40rpx">
          今日可用竞购积分
          <image src="https://aocshop.oss-cn-hangzhou.aliyuncs.com/aoc/2025/9/2968da7edee4b0eb7e9b0feca7.png" mode="scaleToFill" />
        </view>
        <view class="score">{{ availableScore }}</view>
      </view>

      <!-- 助手服务信息 -->
      <view class="middle" style="margin-top: 20rpx;">
        <view class="left">
          <view>智能AI参拍预约助手</view>
          <view>
            已服务 <text style="color: #e8df21;">210天</text>
            剩余 <text style="color: #e8df21;">6</text>天
          </view>
        </view>
        <button class="btn">续费</button>
      </view>

      <!-- 设置积分区域 -->
      <view class="shadowBox">
        <view class="name">设置今日使用竞购积分数</view>

        <!-- 选项1：全部 -->
        <view class="purchaseServices" @click="selectOption(0)">
          <checkBox v-model="selected[0]" :activeColor="'#5756b3'" />
          <view class="purchaseScore">
            <view style="margin-bottom: 20rpx">全部竞购积分: {{ totalScore }}</view>
          </view>
        </view>

        <!-- 选项2：一半 -->
        <view class="purchaseServices" @click="selectOption(1)">
          <checkBox v-model="selected[1]" :activeColor="'#5756b3'" />
          <view class="purchaseScore">
            <view style="margin-bottom: 20rpx">一半竞购积分: {{ halfScore }}</view>
          </view>
        </view>

        <!-- 选项3：自定义 -->
        <view class="purchaseServices" @click="selectOption(2)">
          <checkBox v-model="selected[2]" :activeColor="'#5756b3'" />
          <view class="purchaseScore" style="display: flex; align-items: center;">
            <view style="margin-bottom: 20rpx">自定竟购积分:</view>
            <input
              type="number"
              placeholder="请输入"
              v-model="customValue"
              :disabled="!selected[2]"  
              @click.stop
              style="
                margin-left: 20rpx;
                width: 230rpx;
                height: 50rpx;
                border: 1px solid #c7c3c3;
                border-radius: 30rpx;
                padding-left: 20rpx;
                background-color: #f9f9f9;
                color: #333;
              "
              :style="{ 
                borderColor: selected[2] ? '#c7c3c3' : '#e0e0e0',
                backgroundColor: selected[2] ? '#fff' : '#f5f5f5',
                color: selected[2] ? '#333' : '#ccc'
              }"
            />
          </view>
        </view>

        <!-- 确认按钮 -->
        <button
          class="btn"
          @click="handleConfirm"
          :disabled="!hasSelected"
          v-if="!isConfirmed"
        >
          确认
        </button>

        <!-- 确认后显示 -->
        <view class="complate" v-if="isConfirmed">
          <view>{{ currentTime }}</view>
          <view>已设置</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import classifyHead from "@/components/classifyHead.vue";
import checkBox from "@/components/checkbox.vue";
import { ref, computed, onMounted } from "vue";

// 当前是否已确认
const isConfirmed = ref(false);

// 当前时间
const currentTime = ref('');

// 用户自定义输入值
const customValue = ref('');

// 每个选项的选中状态 [全部, 一半, 自定义]
const selected = ref([false, false, false]);

// 剩余可用积分（从存储中读取）
const availableScore = ref('0.00');

// 总积分（用于计算）
let totalScore = ref('0.00');
let halfScore = ref('0.00');

// 是否至少有一个被选中
const hasSelected = computed(() => selected.value.some(item => item));

// 页面加载时初始化数据
onMounted(() => {
  // 从存储中读取用户累计购买的总积分（初始购买总和）
  const totalBidRaw = Local.get('totalBidScore');
  const totalBid = isNaN(parseFloat(totalBidRaw)) ? 0 : parseFloat(totalBidRaw);

  // 再读取已使用的积分（防止重复使用）
  const usedBidRaw = Local.get('usedBidScore');
  const usedBid = isNaN(parseFloat(usedBidRaw)) ? 0 : parseFloat(usedBidRaw);

  // 计算剩余可用积分
  const remaining = Math.max(0, totalBid - usedBid);

  // 更新显示
  totalScore.value = remaining.toFixed(2);
  halfScore.value = (remaining / 2).toFixed(2);
  availableScore.value = remaining.toFixed(2);
});

// 选择某一项（实现单选）
const selectOption = (index) => {
  selected.value = [false, false, false];
  selected.value[index] = true;
};

// 确认按钮点击：使用积分
const handleConfirm = () => {
  if (!hasSelected.value) {
    uni.showToast({
      title: '请先选择一个积分方案',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  // 获取当前剩余积分
  const totalBidRaw = Local.get('totalBidScore');
  const totalBid = isNaN(parseFloat(totalBidRaw)) ? 0 : parseFloat(totalBidRaw);
  const usedBidRaw = Local.get('usedBidScore');
  const usedBid = isNaN(parseFloat(usedBidRaw)) ? 0 : parseFloat(usedBidRaw);

  let usedThisTime = 0;

  if (selected.value[0]) {
    // 使用全部剩余积分
    usedThisTime = totalBid - usedBid;
  } else if (selected.value[1]) {
    // 使用一半
    usedThisTime = (totalBid - usedBid) / 2;
  } else if (selected.value[2]) {
    // 自定义
    const input = parseFloat(customValue.value);
    if (isNaN(input) || input <= 0) {
      uni.showToast({ title: '请输入有效的积分数', icon: 'none' });
      return;
    }
    const remaining = totalBid - usedBid;
    usedThisTime = Math.min(input, remaining); // 不超过剩余
  }

  // 更新已使用积分
  const newUsedBid = (usedBid + usedThisTime).toFixed(2);
  Local.set('usedBidScore', newUsedBid);

  // 计算新的可用积分
  const newAvailable = (totalBid - parseFloat(newUsedBid)).toFixed(2);

  // 更新页面显示
  availableScore.value = newAvailable;

  // 标记为已确认
  isConfirmed.value = true;
  currentTime.value = getCurrentTime();

  // 发送全局事件，通知其他页面更新（可选）
  uni.$emit('scoreUpdated', { available: newAvailable });

 
};

// 获取当前时间
function getCurrentTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}
</script>

<style lang="scss">
.oneClick {
  .content {
    width: calc(100% - 20rpx);
    padding: 0 10rpx;

    .middle {
      background: #5756b3;
      height: 106rpx;
      width: 690rpx;
      border-radius: 30rpx;
      display: flex;
      justify-content: space-around;
      align-items: center;
      padding: 10rpx 20rpx;

      image {
        width: 30rpx;
        height: 30rpx;
        border-radius: 50%;
      }

      .score {
        width: 200rpx;
        color: aliceblue;
        font-size: 36rpx;
        text-align: right;
      }

      .btn {
        width: 147rpx;
        height: 64rpx;
        border-radius: 50rpx;
        background: #e07002;
        display: flex;
        justify-content: center;
        align-items: center;
        color: aliceblue;
        margin-left: 100rpx;
      }

      .left {
        width: 320rpx;
        margin-left: 75rpx;
      }
    }

    .shadowBox {
      margin-top: 20rpx;
      width: calc(100% - 40rpx);
      padding: 0 20rpx;
      height: 850rpx;
      box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.15);
      border-radius: 30rpx;

      .name {
        font-size: 40rpx;
        width: 100%;
        text-align: center;
        padding-top: 20rpx;
      }

      .purchaseServices {
        margin-top: 20rpx;
        border-radius: 30rpx;
        width: calc(100% - 80rpx);
        height: 170rpx;
        border: 1px solid #c7c3c3;
        display: flex;
        align-items: center;
        padding: 0 40rpx;

        .purchaseScore {
          margin-left: 40rpx;
          display: flex;
          align-items: center;
        }
      }

      .btn {
        background: #5756b3;
        margin-top: 40rpx;
        width: 520rpx;
        height: 100rpx;
        border-radius: 30rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        color: aliceblue;

        &:disabled {
          opacity: 0.6;
          color: #ccc;
        }
      }

      .complate {
        margin-top: 100rpx;
        width: 100%;
        text-align: center;
      }
    }
  }
}
</style>